package com.tbl.modules.wms.controller.baseinfo;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tbl.common.utils.*;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.baseinfo.FactoryArea;
import com.tbl.modules.wms.entity.baseinfo.Shelf;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms.service.baseinfo.CarService;
import com.tbl.modules.wms.service.baseinfo.FactoryAreaService;
import com.tbl.modules.wms.service.baseinfo.ShelfService;
import com.tbl.modules.wms.service.baseinfo.WarehouseService;
import com.tbl.modules.wms.service.webservice.client.WmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 库位列表控制层
 * @author 70486
 */
@Controller
@RequestMapping(value = "/goods")
public class ShelfController extends AbstractController {

    /**
     * 库位信息
     */
    @Autowired
    private ShelfService shelfService;
    /**
     * 日志信息
     */
    @Autowired
    private LogService logService;
    /**
     * 角色信息
     */
    @Autowired
    private RoleService roleService;
    /**
     * wms调用入库
     */
    @Autowired
    private WmsService wmsService;
    /**
     * 行车
     */
    @Autowired
    private CarService carService;
    /**
     * 仓库
     */
    @Autowired
    private WarehouseService warehouseService;
    /**
     * 厂区
     */
    @Autowired
    private FactoryAreaService factoryAreaService;


    /**
     * 跳转到库位列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.goods));
        mv.setViewName("techbloom/baseinfo/goods/goods_list");
        return mv;
    }

    /**
     * 获取库位列表数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(5);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        //仓库id
        map.put("warehouseId", map.get("warehouse"));
        //厂区编码 okk
        map.put("factoryCodeList", getSessionUser().getFactoryCode()!=null?Arrays.asList(getSessionUser().getFactoryCode().split(",")):null);
        //二期用户的所属仓库
        map.put("warehouseIds", getSessionUser().getUserWarehouseIds()!=null?Arrays.asList(getSessionUser().getUserWarehouseIds().split(",")):null);
        PageTbl page = this.getPage();
        PageUtils utils = shelfService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 库位基础数据导出Excel
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response){
        try {
            String sheetName = "库位列表" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("code", "库位编号");
                mapFields.put("locationDesc", "库位描述");
                mapFields.put("factoryCode", "厂区编码");
                mapFields.put("factoryName", "厂区名称");
                mapFields.put("warehouseCode", "仓库编码");
                mapFields.put("warehouseName", "仓库名称");
                mapFields.put("areaName", "库区名称");
                mapFields.put("stateStr", "状态");
                mapFields.put("repeatOccupancyStr", "是否复用");
                mapFields.put("minCapacity", "最小库存量");
                mapFields.put("maxCapacity", "最大库存量");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("code", "库位编号");
                    } else if ("3".equals(s)) {
                        mapFields.put("locationDesc", "库位描述");
                    } else if ("4".equals(s)) {
                        mapFields.put("factoryCode", "厂区编码");
                    } else if ("5".equals(s)) {
                        mapFields.put("factoryName", "厂区名称");
                    } else if ("6".equals(s)) {
                        mapFields.put("warehouseCode", "仓库编码");
                    } else if ("7".equals(s)) {
                        mapFields.put("warehouseName", "仓库名称");
                    } else if ("8".equals(s)) {
                        mapFields.put("areaName", "库区名称");
                    } else if ("9".equals(s)) {
                        mapFields.put("stateStr", "状态");
                    } else if ("10".equals(s)) {
                        mapFields.put("repeatOccupancyStr", "是否复用");
                    } else if ("11".equals(s)) {
                        mapFields.put("minCapacity", "最小库存量");
                    } else if ("12".equals(s)) {
                        mapFields.put("maxCapacity", "最大库存量");
                    }
                }
            }

            //okk
            DeriveExcel.exportExcel(sheetName, shelfService.getExcelList(request.getParameter("ids"), request.getParameter("queryCode"),
                    getSessionUser().getFactoryCode() != null ? Arrays.asList(getSessionUser().getFactoryCode().split(",")) : null,
                    request.getParameter("queryWarehouse"), request.getParameter("queryFactoryCode"), getSessionUser().getUserWarehouseIds()!=null ?
                    Arrays.stream(getSessionUser().getUserWarehouseIds().split(",")).map(Long::parseLong).collect(Collectors.toList()) :
                    null), mapFields, response, "");
            logService.logInsert("库位导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取库位占用率的列表数据
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/getShelfUseProList")
    @ResponseBody
    public Map<String, Object> getShelfUseProList() {
        Map<String, Object> map = new HashMap<>(1);
        PageTbl page = this.getPage();
        String sortName = page.getSortname();
        if (StringUtils.isEmptyString(sortName)) {
            sortName = "";
            page.setSortname(sortName);
        }
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        PageUtils pageList = shelfService.getList(map);
        page.setTotalRows(pageList.getTotalCount() == 0 ? 1 : pageList.getTotalCount());
        map.put("rows", pageList.getList());
        executePageMap(map, page);
        return map;
    }

    /**
     * 获取库位占用率的折线图数据
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getShelfUseProLine")
    @ResponseBody
    public Map<String, Object> getShelfUseProLine() {
        return shelfService.getLine();
    }

    /**
     * 释放库位
     * @param ids 库位主键
     */
    @RequestMapping(value = "/isStart.do")
    @ResponseBody
    public void isStart(Long[] ids) {
        //释放库位
        shelfService.isStart(ids);
        //记录日志
        StringBuffer stringBuffer = new StringBuffer();
        shelfService.selectList(new EntityWrapper<Shelf>().in("ID", ids)).forEach(shelf ->
                stringBuffer.append(shelf.getCode()).append(","));
        logService.logInsertGrenId("用户释放库位！", 101, request, stringBuffer.toString());
    }

    /**
     * 关闭库位
     * @param ids 库位主键
     */
    @RequestMapping(value = "/disMiss.do")
    @ResponseBody
    public void disMiss(Long[] ids) {
        //关闭库位
        shelfService.disMiss(ids);
        //记录日志
        StringBuffer stringBuffer = new StringBuffer();
        shelfService.selectList(new EntityWrapper<Shelf>().in("ID", ids)).forEach(shelf ->
                stringBuffer.append(shelf.getCode()).append(","));
        logService.logInsertGrenId("用户关闭库位！", 102, request, stringBuffer.toString());
    }

    /**
     * 库位状态全部置为可用
     */
    @RequestMapping(value = "/allRelease.do")
    @ResponseBody
    public void allRelease() {
        //把库位全部释放
        shelfService.setAllStatesUseful();
        //记录日志
        logService.logInsertGrenId("不得了了啊！你胆敢把库位全部释放啊！", 103, request, "");
    }

    /**
     * 同步库位基础数据
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/synchronousdata.do")
    @ResponseBody
    public Map<String,Object> synchronousdata() {
    	try {
			logger.info(DateUtils.getTime()+" >>同步库位基础数据....");
            Map<String, Object> xmlMap = new HashMap<>(1);
	        xmlMap.put("line", new HashMap<String, Object>(3) {{
	            put("warehouseno", "");
	            put("warehousename", "");
	            put("orgid","");
	        }});
	        wmsService.FEWMS014(xmlMap);
		} catch (Exception e) {
			e.printStackTrace();
		}

        Connection conn = JDBCUtils.getConnection();
        PreparedStatement pst = null;
        // 创建执行存储过程的对象
        CallableStatement proc = null;
        try {
            proc = conn.prepareCall("{ call EBS2WMS_YDDL_VWKG_SHELF() }");
            // 执行
            proc.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭IO流
                proc.close();
                JDBCUtils.closeAll(null, pst, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new HashMap<String,Object>(2) {{
            put("result", true);
            put("msg", "更新成功！");
        }};
    }

    /**
     * 根据厂区、仓库获取对应的库位
     * @param warehouseId 仓库主键
     * @param factoryCode 厂区编码
     * @param queryString 模糊查询条件
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/getShelfByFactoryWarehouse.do")
    @ResponseBody
    public Map<String, Object> getShelfByFactoryWarehouse(Long warehouseId,String factoryCode, String queryString,int pageSize,int pageNo) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("warehouseId", warehouseId);
        map.put("queryString", queryString.toUpperCase());
        map.put("factoryCode", factoryCode);
        PageTbl page = this.getPage();
        page.setPageno(pageNo);
        page.setPagesize(pageSize);
        PageUtils utils = shelfService.getShelfByFactoryWarehouse(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("result", utils.getList());
        map.put("total", utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        return map;
    }

    /**
     * 根据厂区编码、仓库编码获取对应的库位
     * @param warehouseCode 仓库编码
     * @param entityId 公司（实体）ID
     * @param queryString 模糊查询条件
     * @param pageSize 页大小（分页）
     * @param pageNo 页码（分页）
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/getShelfByFactWareCode.do")
    @ResponseBody
    public Map<String, Object> getShelfByFactWareCode(String warehouseCode,String entityId,String factorycode,String queryString,int pageSize,int pageNo) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("warehouseCode", warehouseCode);
        map.put("factorycode", factorycode);
        map.put("queryString", queryString.toUpperCase());
        map.put("entityId", entityId);
        PageTbl page = this.getPage();
        page.setPageno(pageNo);
        page.setPagesize(pageSize);
        PageUtils utils = shelfService.getShelfByFactWareCode(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("result", utils.getList());
        map.put("total", utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        return map;
    }

    /**
     * 不可复用
     * @param ids 库位主键
     */
    @RequestMapping(value = "/unMltiplexing.do")
    @ResponseBody
    public void unMltiplexing(Long[] ids) {
        Shelf shelfEntity = new Shelf();
        shelfEntity.setRepeatOccupancy(Constant.INT_ZERO);
        shelfService.update(shelfEntity, new EntityWrapper<Shelf>().in(ids!=null && ids.length>0,"ID", ids));

        //记录日志
        StringBuffer stringBuffer = new StringBuffer();
        shelfService.selectList(new EntityWrapper<Shelf>().in("ID", ids)).forEach(shelf ->
                stringBuffer.append(shelf.getCode()).append(","));
        logService.logInsertGrenId("把库位设为不可复用！", 104, request, stringBuffer.toString());
    }

    /**
     * 可复用
     * @param ids 库位主键
     */
    @RequestMapping(value = "/mltiplexing.do")
    @ResponseBody
    public void mltiplexing(Long[] ids) {
        Shelf shelfEntity = new Shelf();
        shelfEntity.setRepeatOccupancy(Constant.INT_ONE);
        shelfService.update(shelfEntity, new EntityWrapper<Shelf>().in(ids!=null && ids.length>0,"ID", ids));

        //记录日志
        StringBuffer stringBuffer = new StringBuffer();
        shelfService.selectList(new EntityWrapper<Shelf>().in("ID", ids)).forEach(shelf ->
                stringBuffer.append(shelf.getCode()).append(","));
        logService.logInsertGrenId("把库位设为可以复用！", 105, request, stringBuffer.toString());
    }

    /**
     * 废弃库位
     * @param ids 库位主键
     */
    @RequestMapping(value = "/discardShelf.do")
    @ResponseBody
    public void discardShelf(Long[] ids) {
        Shelf shelfEntity = new Shelf();
        shelfEntity.setState(199);
        shelfService.update(shelfEntity, new EntityWrapper<Shelf>().in(ids!=null && ids.length>0,"ID", ids));

        //记录日志
        StringBuffer stringBuffer = new StringBuffer();
        shelfService.selectList(new EntityWrapper<Shelf>().in("ID", ids)).forEach(shelf ->
                stringBuffer.append(shelf.getCode()).append(","));
        logService.logInsertGrenId("把库位废弃！", 106, request, stringBuffer.toString());
    }

    /**
     * 激活库位
     * @param ids 库位主键
     */
    @RequestMapping(value = "/activeShelf.do")
    @ResponseBody
    public void activeShelf(Long[] ids) {
        Shelf shelfEntity = new Shelf();
        shelfEntity.setState(1);
        shelfService.update(shelfEntity, new EntityWrapper<Shelf>().in(ids!=null && ids.length>0,"ID", ids));

        //记录日志
        List<Shelf> lstShelf = shelfService.selectList(new EntityWrapper<Shelf>().in("ID", ids));
        StringBuffer stringBuffer = new StringBuffer();
        lstShelf.forEach(shelf -> stringBuffer.append(shelf.getCode()).append(","));
        logService.logInsertGrenId("把库位激活！", 107, request, stringBuffer.toString());
    }

    /**
     * 弹出到库位添加、编辑页面
     * @param id 库位主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/baseinfo/goods/goods_edit");
        //okk
        mv.addObject("shelf", shelfService.findShelfById(id, getSessionUser().getFactoryCode()));
        mv.addObject("warehouseAreaList" , carService.selectWarehouseArea());
        return mv;
    }

    /**
     * 保存库位信息
     * @param shelf 库位
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveGoods")
    @ResponseBody
    public Map<String, Object> saveGoods(Shelf shelf) {
        Map<String, Object> map = new HashMap<>(2);
        Warehouse warehouse = StringUtils.isENChar(shelf.getWarehouseCode()) ? warehouseService.selectOne(new EntityWrapper<Warehouse>()
                .eq("CODE",shelf.getWarehouseCode())
                .eq("FACTORYCODE",shelf.getFactoryCode())) : warehouseService.selectById(shelf.getWarehouseCode());
        FactoryArea factoryArea = factoryAreaService.selectOne(new EntityWrapper<FactoryArea>().eq("CODE", shelf.getFactoryCode()));
        shelf.setWarehouseCode(warehouse.getCode());
        shelf.setComplete(warehouse.getCode()+"-"+factoryArea.getOrganizationCode());
        shelf.setCodeComplete(shelf.getCode()+"/"+warehouse.getCode()+"-"+factoryArea.getOrganizationCode());
        List<Shelf> lstShelf = shelfService.selectList(new EntityWrapper<Shelf>().eq("CODE_COMPLETE", shelf.getCodeComplete()));
        //不能新增重复库位
        if (lstShelf.size()>0 && !lstShelf.get(0).getId().equals(shelf.getId())){
            map.put("result", false);
            map.put("msg", "不能新增重复编码的库位！");
        }else{
            boolean result = shelfService.insertOrUpdate(shelf);
            map.put("result", result);
            map.put("msg",result ? "保存成功！" : "保存失败！");
        }
        return map;
    }

    /**
     * 删除库位信息
     * @param ids 库位主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteCars.do")
    @ResponseBody
    public Map<String, Object> deleteCars(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result = shelfService.deleteBatchIds(StringUtils.stringToList(ids));
        map.put("result", result);
        map.put("msg", result?"删除成功！":"删除失败！");
        return map;
    }
}
